package server.communication.listeners;

import server.repositories.AccountRepository;
import server.threads.ServerCommunicator;
import message.BulkUpdateRequestMessage;
import message.BulkUpdateResponseMessage;
import message.Message;
import message.ServerMessageWrapper;
import communication.MessageListener;
import communication.MessageReceivedEvent;

public class BulkUpdateRequestListener implements MessageListener
{
	private final ServerCommunicator communicator;
	private final AccountRepository accountRepository;
	
	public BulkUpdateRequestListener(ServerCommunicator communicator, AccountRepository accountRepository)
	{
		this.communicator = communicator;
		this.accountRepository = accountRepository;
	}
	
	@Override
	public void messageRecieved(MessageReceivedEvent e)
	{
		ServerMessageWrapper message = ((ServerMessageWrapper) e.getMessage());
		BulkUpdateRequestMessage innerMessage = (BulkUpdateRequestMessage) message.internalMessage;
		BulkUpdateResponseMessage responseMessage = new BulkUpdateResponseMessage();
		
		responseMessage.setUpdatedAccounts(accountRepository.getUpdatedAfter(innerMessage.getLastSynchronizeTimestamp()));
		responseMessage.setInsertedAccounts(accountRepository.getInsertedAfter(innerMessage.getLastSynchronizeTimestamp()));
		
		System.out.println("inserted: " + responseMessage.getInsertedAccounts());
		System.out.println("updated: " + responseMessage.getUpdatedAccounts());
		
		communicator.sendMessage(message.connectionId, responseMessage);
	}

	@Override
	public boolean acceptsMessage(Message message)
	{
		if (message.getClass().equals(ServerMessageWrapper.class))
			message = ((ServerMessageWrapper) message).internalMessage;
		
		return message.getClass().equals(BulkUpdateRequestMessage.class);
	}
}
